package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoping
 * @create 2020/7/1 15:05
 * @since 1.0.0
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;

    /**
     * 无需登录就可访问
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     * 查询员工信息
     * @param model
     * @param session
     * @param token     登录凭证
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token",required = false) String token){
        if (!StringUtils.isEmpty(token)){
            //因为认证服务系统语言环境存在未知性，所以采用 HttpClient/RestTemplate 请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
            //获取请求体信息
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null){
            //没登陆,跳转登录页面,带上自己的请求路径
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client1.com:8081/employees";
        }
        List<String> emps = new ArrayList<>();
        emps.add("小平");
        emps.add("小美");
        model.addAttribute("emps",emps);
        return "list";
    }


}
